'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class CarModel extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.Model.belongsTo(models.Series, {as: 'series'})
    }
  }
  CarModel.init({
    seriesId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {msg: '车型ID不能为空'},
        isInt: {msg: '车型ID必须为整数'}
      }
    },
    nameZh: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '中文车型名称必填'},
        notEmpty: {msg: '中文车型名称不能为空'},
        len: {
          args: [2, 255],
          msg: '中文车型名称长度在2-45个字符之间'
        },
        async isUnique(value) {
          const model = await CarModel.findOne({ where: { nameZh: value } })
          if (model) {
            throw new Error('中文车型名称已经存在。');
          }
        }
      }
    },
    nameEn: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '英文车型名称必填'},
        notEmpty: {msg: '英文车型名称不能为空'},
        len: {
          args: [2, 255],
          msg: '英文车型名称长度在2-45个字符之间'
        },
        async isUnique(value) {
          const model = await CarModel.findOne({ where: { nameEn: value } })
          if (model) {
            throw new Error('英文车型名称已经存在。');
          }
        }
      }
    },
    descriptionZh: DataTypes.TEXT,
    descriptionEn: DataTypes.TEXT,
    img: {
      type: DataTypes.TEXT,
      allowNull: false,
      validate: {
        notNull: {msg: '车型图片不能为空'},
        // isUrl: {msg: '车型图片必须为URL'}
      }
    },
    year: DataTypes.INTEGER,
    launchDate: DataTypes.DATE
  }, {
    sequelize,
    modelName: 'Model',
  });
  return CarModel;
};